<template>
  <div class="cart">
    <h4>全部商品</h4>
    <div class="cart-main">
      <div class="cart-th">
        <div class="cart-th1">全部</div>
        <div class="cart-th2">商品</div>
        <div class="cart-th3">单价（元）</div>
        <div class="cart-th4">数量</div>
        <div class="cart-th5">小计（元）</div>
        <div class="cart-th6">操作</div>
      </div>
      <div class="cart-body">
        <ul class="cart-list" v-for="cartInfo in cartInfoList" :key="cartInfo.skuId">
          <li class="cart-list-con1">
            <input type="checkbox" name="chk_list" :checked="cartInfo.isChecked === 1 ? true : false"
              @input="changeSingle(cartInfo.skuId, cartInfo.isChecked === 1 ? 0 : 1)">
          </li>
          <li class="cart-list-con2">
            <img :src="cartInfo.imgUrl">
            <div class="item-msg">{{ cartInfo.skuName }}</div>
          </li>
          <li class="cart-list-con3">
            <div class="item-txt">语音升级款</div>
          </li>
          <li class="cart-list-con4">
            <span class="price">{{ cartInfo.skuPrice }}</span>
          </li>
          <li class="cart-list-con5">
            <a href="javascript:void(0)" class="mins" @click="upDateNum(cartInfo, -1)">-</a>
            <input autocomplete="off" type="text" :value="cartInfo.skuNum" @change="changeNum($event, cartInfo)"
              minnum="1" class="itxt" @focus="changeOldNum(cartInfo.skuNum)">
            <a href="javascript:void(0)" class="plus" @click="upDateNum(cartInfo, 1)"> +</a>
          </li>
          <li class=" cart-list-con6">
            <span class="sum">{{ cartInfo.skuPrice * cartInfo.skuNum }}</span>
          </li>
          <li class="cart-list-con7">
            <a href="javascript:;" class="sindelet" @click="deleteSingle(cartInfo.skuId)">删除</a>
            <br>
            <a href="#none">移到收藏</a>
          </li>
        </ul>
      </div>
    </div>
    <div class="cart-tool">
      <div class="select-all">
        <input class="chooseAll" type="checkbox" v-model="allChecked">
        <span>全选</span>
      </div>
      <div class="option">
        <a href="javascript:;" @click="deleteAllChecked">删除选中的商品</a>
        <a href="#none">移到我的关注</a>
        <a href="#none">清除下柜商品</a>
      </div>
      <div class="money-box">
        <div class="chosed">已选择
          <span>{{ allNum }}</span>件商品
        </div>
        <div class="sumprice">
          <em>总价（不含运费） ：</em>
          <i class="summoney">{{ allPrice }}</i>
        </div>
        <div class="sumbtn">
          <router-link to="/trade" class="sum-btn">结算</router-link>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getShopCart, getSingleChecked, getDeleteSingle, getAllChecked, getAddCartSuccess, deleteChecked } from '@/api';

export default {
  name: 'ShopCart',
  data () {
    return {
      cartInfoList: [],
      //保存数量的旧值
      oldNum: 1,
    }
  },
  mounted () {
    //调用初始化购物车数据的函数
    this.reqShopCartList()
  },
  computed: {
    //控制全选与反选
    allChecked: {
      get () {
        return this.cartInfoList?.every(item => {
          return item.isChecked === 1
        })
      },
      async set (newVal) {
        try {
          //将所有商品的id收集为一个数组
          const skuIdList = this.cartInfoList.map(item => {
            return item.skuId
          })
          await getAllChecked(newVal ? 1 : 0, skuIdList)
          //全选后重新渲染数据
          this.reqShopCartList()
        } catch (error) {
          alert(error.message)
        }
      }
    },
    //计算商品总数量
    allNum () {
      return this.cartInfoList.reduce((p, c) => {
        if (c.isChecked === 1) {
          p += c.skuNum
        }
        return p
      }, 0)
    },
    //计算商品总价格
    allPrice () {
      return this.cartInfoList.reduce((p, c) => {
        if (c.isChecked === 1) {
          p += c.skuNum * c.skuPrice
        }
        return p
      }, 0)
    }
  },
  methods: {
    //1.请求购物车数据的方法
    async reqShopCartList () {
      try {
        const res = await getShopCart()
        // console.log(res);
        // this.cartInfoList = res[0]?.cartInfoList
        this.cartInfoList = res[0]?.cartInfoList.map(item => {
          item.isReq = false ////给每一个商品对象数据都设置一个默认false的是否在请求状态
          return item
        })
      } catch (error) {
        alert(error.message)
      }
    },
    //2.请求单个商品修改勾选状态（第二个参数不是布尔值，0代表取消选中 1代表选中）
    async changeSingle (skuId, isChecked) {
      try {
        await getSingleChecked(skuId, isChecked)
        //修改之后重新请求最新数据
        this.reqShopCartList()
      } catch (error) {
        alert(error.message)
      }
    },
    //3.删除单个商品数据
    async deleteSingle (skuId) {
      try {
        await getDeleteSingle(skuId)
        //删除之后重新请求最新数据
        this.reqShopCartList()
      } catch (error) {
        alert(error.message)
      }
    },
    //4.点击按钮累加或累减
    async upDateNum (cartInfo, num) {
      try {
        //1.判断是否有数据的数量正在被修改，如果为真，则直接return，不允许再次连续修改
        if (cartInfo.isReq) return
        //2.此时上面的判断结果为false，所以进到这里，那么说明准备去修改数量了，需要立即将开关打开，变成正在修改数据的状态
        cartInfo.isReq = true
        //判断计算后商品的数量小于等于0,则不能再操作
        //5.这里判断临界值也有一个return，它会让正在修改数据的状态同时return，所以当数量被修改为<=0的值时，需要关闭阀门，变成没有修改数量请求的状态
        if (cartInfo.skuNum + num <= 0) return cartInfo.isReq = false
        await getAddCartSuccess(cartInfo.skuId, num)
        //修改之后重新请求最新数据
        //6.需要await等待重新请求完成才可以下一步的执行
        await this.reqShopCartList()
        //3.待修改商品数量完成并且重新渲染完成后把开关关掉，代表暂时没有修改数量的请求
        cartInfo.isReq = false
      } catch (error) {
        //4.当修改数量的请求失败时，那么也要关闭阀门，变成没有修改数量请求的状态
        cartInfo.isReq = false
        alert(error.message)
      }
    },
    //5.批量删除已选中商品
    async deleteAllChecked () {
      try {
        const arr = []
        this.cartInfoList.forEach(item => {
          if (item.isChecked === 1) {
            arr.push(item.skuId)
          }
        })
        await deleteChecked(arr)
        //删除之后重新请求最新数据
        this.reqShopCartList()
      } catch (error) {
        alert(error.message)
      }
    },
    // async deleteAllChecked () {
    //   try {
    //     const list = this.cartInfoList.reduce((p, c) => {
    //       if (c.isChecked === 1) {
    //         p.push(c.skuId)
    //       }
    //     }, [])
    //     await deleteChecked(list)
    //     //删除之后重新请求最新数据
    //     this.reqShopCartList()
    //   } catch (error) {
    //     alert(error.message)
    //   }
    // }

    //6.校验输入框的内容
    async changeNum (e, cartInfo) {
      const reg = /^[0-9]+$/g
      //判断修改后并失去焦点的值是否符合正则，如果不符合或者数量<=0则把设置的oldNum替换掉那个不合规则的值，并return
      if (!reg.test(e.target.value) || e.target.value <= 0) {
        e.target.value = this.oldNum
        return
      }
      //校验通过后发起修改请求
      //首先计算出来改变的差值，因为后台需要的就是差值
      const centerNum = e.target.value - cartInfo.skuNum
      try {
        await getAddCartSuccess(cartInfo.skuId, centerNum)
        //修改之后重新请求最新数据
        await this.reqShopCartList()
      } catch (error) {
        alert(error.message)
      }
    },
    //7.针对商品数量的获取焦点事件
    changeOldNum (skuNum) {
      //只要获取焦点 就把当前表单的值设置给oldNum
      this.oldNum = skuNum
    }
  }
}
</script>

<style lang="less" scoped>
.cart {
  width: 1200px;
  margin: 0 auto;

  h4 {
    margin: 9px 0;
    font-size: 14px;
    line-height: 21px;
  }

  .cart-main {
    .cart-th {
      background: #f5f5f5;
      border: 1px solid #ddd;
      padding: 10px;
      overflow: hidden;

      &>div {
        float: left;
      }

      .cart-th1 {
        width: 25%;

        input {
          vertical-align: middle;
        }

        span {
          vertical-align: middle;
        }
      }

      .cart-th2 {
        width: 25%;
      }

      .cart-th3,
      .cart-th4,
      .cart-th5,
      .cart-th6 {
        width: 12.5%;

      }
    }

    .cart-body {
      margin: 15px 0;
      border: 1px solid #ddd;

      .cart-list {
        padding: 10px;
        border-bottom: 1px solid #ddd;
        overflow: hidden;

        &>li {
          float: left;
        }

        .cart-list-con1 {
          width: 4.1667%;
        }

        .cart-list-con2 {
          width: 25%;

          img {
            width: 82px;
            height: 82px;
            float: left;
          }

          .item-msg {
            float: left;
            width: 150px;
            margin: 0 10px;
            line-height: 18px;
          }
        }

        .cart-list-con3 {
          width: 20.8333%;

          .item-txt {
            text-align: center;
          }
        }

        .cart-list-con4 {
          width: 12.5%;

        }

        .cart-list-con5 {
          width: 12.5%;

          .mins {
            border: 1px solid #ddd;
            border-right: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }

          input {
            border: 1px solid #ddd;
            width: 40px;
            height: 33px;
            float: left;
            text-align: center;
            font-size: 14px;
          }

          .plus {
            border: 1px solid #ddd;
            border-left: 0;
            float: left;
            color: #666;
            width: 6px;
            text-align: center;
            padding: 8px;
          }
        }

        .cart-list-con6 {
          width: 12.5%;

          .sum {
            font-size: 16px;
          }
        }

        .cart-list-con7 {
          width: 12.5%;

          a {
            color: #666;
          }
        }
      }
    }
  }

  .cart-tool {
    overflow: hidden;
    border: 1px solid #ddd;

    .select-all {
      padding: 10px;
      overflow: hidden;
      float: left;

      span {
        vertical-align: middle;
      }

      input {
        vertical-align: middle;
      }
    }

    .option {
      padding: 10px;
      overflow: hidden;
      float: left;

      a {
        float: left;
        padding: 0 10px;
        color: #666;
      }
    }

    .money-box {
      float: right;

      .chosed {
        line-height: 26px;
        float: left;
        padding: 0 10px;
      }

      .sumprice {
        width: 200px;
        line-height: 22px;
        float: left;
        padding: 0 10px;

        .summoney {
          color: #c81623;
          font-size: 16px;
        }
      }

      .sumbtn {
        float: right;

        a {
          display: block;
          position: relative;
          width: 96px;
          height: 52px;
          line-height: 52px;
          color: #fff;
          text-align: center;
          font-size: 18px;
          font-family: "Microsoft YaHei";
          background: #e1251b;
          overflow: hidden;
        }
      }
    }
  }
}
</style>